<template>
  <Spin :spinning="loading">
    <BasicForm @register="register" v-bind="$attrs" />
    <div class="btn-box" v-if="updataFlag">
      <Button type="primary" @click="handleEdit" :loading="loading">确认修改</Button>
      <Button @click="handleCancel">取消</Button>
    </div>
  </Spin>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { editPasswordForm } from '../personalCenter.data';
  import { Button, Spin } from 'ant-design-vue';
  import { EditUserProfilePassWord } from '/@/api/sys/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  const $emits = defineEmits(['updata', 'success', 'update:loading']);
  defineProps({
    updataFlag: {
      type: Boolean,
      default: false,
    },
  });

  const { createMessage } = useMessage();
  const loading = ref<boolean>(false);

  const [register, { updateSchema, validate }] = useForm({
    labelWidth: 0,
    baseColProps: {
      span: 24,
    },
    layout: 'vertical',
    rulesMessageJoinLabel: true,
    schemas: editPasswordForm,
    showActionButtonGroup: false,
  });
  const handleEdit = async () => {
    let values = await validate();
    loading.value = true;
    delete values.alignPassword;
    try {
      await EditUserProfilePassWord(values);
      createMessage.success('更新成功，下次登录请使用新密码');
      handleCancel();
    } catch (e) {
      console.log(e);
    } finally {
      loading.value = false;
    }
  };
  const handleCancel = () => {
    $emits('success');
  };

  $emits('updata', updateSchema);
</script>

<style lang="less" scoped>
  .btn-box {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    .ant-btn {
      & + .ant-btn {
        margin-left: 24px;
      }
    }
  }
</style>
